package com.qzw.security.spring.config;


import com.qzw.security.api.dict.StatusDict;
import com.qzw.security.api.model.User;
import com.qzw.security.api.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserInfoService implements UserDetailsService {
    @Autowired
    private IUserService service;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = new User();
        user.setUsername(s);
        user = service.findOne(user);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        if (!user.getStatus().equals(StatusDict.SUCCESS)) {
            throw new DisabledException("账号不可用");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> permissions = service.findPermissionsByUser(user);
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }
        return new UserInfo(authorities, user.getUsername(), user.getPassword(), user.getId());
    }
}
